(function () {

    var WX_OAUTH2_CODE_URI = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    var REGISTER_URI = 'http://dumo.boxiaomedia.com/Login/register';

    var code_config = {
        appid: "wxab95e95b72aa87a9",
        redirect_uri: window.location.href,
        response_type: 'code',
        scope: 'snsapi_userinfo'
    };

    var parse_query = function (s) {
        var obj = {};
        var a = s.substr(1).split('&');
        for (var i = 0; i < a.length; i++) {
            var b = a[i].split('=');
            obj[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
        }
        return obj;
    };

    /* 手动授权 */
    var manual = function () {
        window.location.href = WX_OAUTH2_CODE_URI + '?' + $.param(code_config) + '#wechat_redirect';
    };

    var post = function (url, data, callback) {
        $.ajax({
            type: 'post',
            processData: false,
            dataType: 'json',
            url: url,
            data: JSON.stringify(data),
            success: function (res) {
                if (callback) {
                    callback(res);
                }
            }
        });
    };

    window.post = post;

    /* 获取用户信息 */
    var cache_user = function () {
        var query;
        if ($.cookie('runtime') != 'pc') {
            query = parse_query(window.location.search);
            if (query.code == null) {
                manual();
            } else {
                post(REGISTER_URI, {
                    code: query.code,
                    apptype: "wxweb"
                }, function (res) {
                    if (res.code == 0) {
                        $.cookie('user', res.data);
                    } else {
                        console.log(res);
                    }
                });
            }
        } else {
            post(REGISTER_URI, {
                code: $.cookie('code'),
                apptype: "wxweb"
            }, function (res) {
                if (res.code == 0 && res.data != null) {
                    $.cookie('user', res.data);
                } else {
                    console.log(res);
                }
            });
        }
    };

    $(function () {
        //if ($.cookie('user') == null) {
        //    cache_user();
        //}
    });
})();